package org.example.logic

import java.util

import com.alibaba.fastjson.{JSON, JSONObject}
import org.example.common.Logging
import org.example.utils.CommonUtils
import org.apache.commons.collections.MapUtils
import org.apache.commons.lang3.StringUtils
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, Seconds}
import redis.clients.jedis.Jedis

/**
 * @Description 自定义报警生成逻辑
 * @Date  2021/7/13
 **/
object AlarmTrigger extends Logging{
  /**
    * 超速报警：定位数据中速度超过阀值
    * @param speed 速度
    * @param threshold 阀值
    * @return
    */
  def isOverspeed(speed: String, threshold: Double): Boolean = {
    if (speed.toDouble > threshold) {
      true
    } else {
      false
    }
  }

  /**
    * 夜间超速报警：夜间定位数据中，速度超过阀值
    * @param speed
    * @param threshold
    * @param time
    * @param riskTimeDeploy
    * @return
    */
  def isOverspeed(speed: String, threshold: Double, time: String, riskTimeDeploy: (Int, Int)): Boolean = {
    if (StringUtils.isNotEmpty(time)) {
      val dateTime = DateTime.parse(time, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
      val minute: Int = dateTime.getMinuteOfDay
      //获取夜间时间区间
      val start_time = riskTimeDeploy._1
      val end_time = riskTimeDeploy._2
      if ((minute >= start_time || minute < end_time) && speed.toDouble > threshold) {
        true
      } else {
        false
      }
    } else {
      false
    }
  }

  /**
    * 连续超速报警：在行驶周期内存在相邻两个报警周期内定位数据中速度超过阀值
    * @param speed 记录仪速度
    * @param threshold 速度报警阈值
    * @param id 车牌号#车牌颜色
    * @param time 定位时间
    * @param message 单条gps数据全量
    * @param warnKey 报警code
    * @param intervalPeriodTime 固定报警事件间隔
    * @param redis
    * @return
    */
  def isOverspeedContinuous(speed: String, threshold: Double, id: String, time: String,
                            message: JSONObject, warnKey: String, intervalPeriodTime: Int, redis: Jedis): Tuple2[Boolean, JSONObject] = {
    if (speed.toDouble > threshold) {
      //gps定位时间
      val times: DateTime = DateTime.parse(time, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
      //行驶周期开始
      val driving_time: Long = PeriodProcess.getDrivingPeriodStart(id, times.getMillis, redis)
      val driving: DateTime = new DateTime(driving_time)
      //计算周期内时间差
      val seconds: Int = Seconds.secondsBetween(driving, times).getSeconds
      //计算该报警位于哪个固定周期内
      val period: Int = seconds / intervalPeriodTime
      //获取Redis中存储的周期内报警数据
      val value: String = redis.hget(warnKey, id)
      if (value != null) {
        val arr = value.split("\\|")
        val mess = arr(0)
        val drivingPeriod = arr(1)
        if (drivingPeriod.equals(driving_time.toString)) {
          val nObject: JSONObject = JSON.parseObject(mess)
          //获取报警时间
          val datetime: String = nObject.getString("dateTime")
          val datatime: DateTime = DateTime.parse(datetime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
          //上一条数据的周期
          val last_period: Int = Seconds.secondsBetween(driving, datatime).getSeconds / intervalPeriodTime
          val diff: Int = period - last_period
          if (diff == 1) {
            redis.hset(warnKey, id, message.toJSONString + "|" + driving_time)
            (true, JSON.parseObject(mess))
          } else {
            redis.hset(warnKey, id, message.toJSONString + "|" + driving_time)
            (false, null)
          }
        } else {
          redis.hset(warnKey, id, message.toJSONString + "|" + driving_time)
          (false, null)
        }
      } else {
        redis.hset(warnKey, id, message.toJSONString + "|" + driving_time)
        (false, null)
      }
    } else {
      (false, null)
    }
  }

  /**
    * 连续夜间超速报警：夜间行驶时段在一个行驶周期中，相邻两个时间段，速度超过阀值
    *
    * @param speed 记录仪速度
    * @param threshold 速度报警阈值
    * @param id 车牌号#车牌颜色
    * @param time 定位时间
    * @param message 单条gps数据全量
    * @param warnKey 报警code
    * @param intervalPeriodTime 固定报警事件间隔
    * @param redis
    * @param riskTimeDeploy 夜间时间段
    * @return
    */
  def isOverspeedContinuous(speed: String, threshold: Double, id: String, time: String,
                            message: JSONObject, warnKey: String, intervalPeriodTime: Int,
                            redis: Jedis, riskTimeDeploy: (Int, Int)): Tuple2[Boolean, JSONObject] = {
    if (StringUtils.isNotEmpty(time)) {
      val dateTime = DateTime.parse(time, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
      val minute: Int = dateTime.getMinuteOfDay
      //获取日间时间区间
      val start_time = riskTimeDeploy._1
      val end_time = riskTimeDeploy._2
      if ((minute >= start_time || minute < end_time) && speed.toDouble > threshold) {
        //行驶周期开始
        val times: DateTime = DateTime.parse(time, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
        val driving_time: Long = PeriodProcess.getDrivingPeriodStart(id, times.getMillis, redis)
        val driving: DateTime = new DateTime(driving_time)
        //计算周期内时间差
        val seconds: Int = Seconds.secondsBetween(driving, times).getSeconds
        //计算该报警位于哪个固定周期内
        val period: Int = seconds / intervalPeriodTime
        //获取Redis中存储的周期内报警数据
        val value: String = redis.hget(warnKey, id)
        if (value != null) {
          val arr = value.split("\\|")
          val mess = arr(0)
          val drivingPeriod = arr(1)
          if (drivingPeriod.equals(driving_time.toString)) {
            val nObject: JSONObject = JSON.parseObject(mess)
            //获取报警时间
            val datetime: String = nObject.getString("dateTime")
            val datatime: DateTime = DateTime.parse(datetime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
            //上一条数据的周期
            val last_period: Int = Seconds.secondsBetween(driving, datatime).getSeconds / intervalPeriodTime
            val diff: Int = period - last_period
            if (diff == 1) {
              redis.hset(warnKey, id, message.toJSONString + "|" + driving_time)
              (true, JSON.parseObject(mess))
            } else {
              redis.hset(warnKey, id, message.toJSONString + "|" + driving_time)
              (false, null)
            }
          } else {
            redis.hset(warnKey, id, message.toJSONString + "|" + driving_time)
            (false, null)
          }
        } else {
          redis.hset(warnKey, id, message.toJSONString + "|" + driving_time)
          (false, null)
        }
      } else {
        (false, null)
      }
    } else {
      (false, null)
    }
  }

  /**
    * 连续驾驶4小时超时报警：定位数据中，驾驶员（未关联到驾驶员的按车辆）连续驾驶（断电不超过20分钟）超过4小时的生成报警
    *
    * @param time
    * @param primaryKey
    * @param jedis
    * @return
    */
  def driver4hour(time: String, primaryKey: String, speed: String, jedis: Jedis): (Boolean, Int) = {
    val forPattern = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
    val id = primaryKey
    var flag: Boolean = false
    var drivingTime = 0
    if (!time.isEmpty) {
      //当前车辆驾驶信息
      val driverInfo: util.Map[String, String] = jedis.hgetAll("driverInfo:" + primaryKey)
      //当前车辆驾驶人
      var driverName = ""
      //人脸识别业务时间
      var businessTime = ""
      if (MapUtils.isNotEmpty(driverInfo) && driverInfo.containsKey("driverName")) {
        driverName = driverInfo.get("driverName")
        businessTime = driverInfo.get("businessTime")
      }

      //获取缓存中连续驾驶车辆时长统计
      val data: String = jedis.hget("more4hours", id)
      //速度为0时时长统计
      val data1: String = jedis.hget("speedZero", id)
      if (data != null) {
        val arr: Array[String] = data.split("\\|")
        //上次累计时长
        val d_value: Int = arr(0).toInt
        //上次记录时间
        val original_time: String = arr(1)
        driverName = CommonUtils.getCurrDriver(driverName, businessTime, original_time, d_value, forPattern)

        //上次驾驶人
        var oldDriverName = ""
        if (arr.size == 3) {
          oldDriverName = arr(2)
        }
        val dateTime_o = DateTime.parse(original_time, forPattern)
        val dateTime_n = DateTime.parse(time, forPattern)
        val seconds = Seconds.secondsBetween(dateTime_o, dateTime_n).getSeconds
        var intervalSecond = seconds
        var oldTime = time
        //如果接收到迟到数据，记此次间隔时间为0，当前存入Redis时间为上次记录的时间
        if (seconds < 0) {
          oldTime = original_time
          intervalSecond = 0
        }
        //断电超过20分钟,新增速度为0判断条件
        if (seconds >= 20 * 60 || (!"".equals(driverName) && !"".equals(oldDriverName) && !driverName.equals(oldDriverName))) {
          jedis.hset("more4hours", id, "0|" + oldTime + "|" + driverName)
          //周期重新累计时，删除挪车点
          jedis.hdel("5timesmap", id)
          flag = false
        } else if (speed.toDouble > 0) { //断电不超过20分钟
          //时间累计
          val cumulative_time = intervalSecond + d_value
          //累计时间小于4小时不生成报警
          if (cumulative_time < 240 * 60) {
            flag = false
          } else if (cumulative_time >= 240 * 60) {
            val minutes_num: String = jedis.hget("alm20min", id)
            if (minutes_num != null) {
              val time1: DateTime = DateTime.parse(minutes_num, forPattern)
              val tim_n = Seconds.secondsBetween(time1, dateTime_n).getSeconds
              if (tim_n > 20 * 60) {
                flag = true
                //重置20分钟的第一次报警时间
                jedis.hset("alm20min", id, oldTime)
                //驾驶时长
                drivingTime = cumulative_time
              } else {
                flag = false
              }
            } else {
              //生成报警
              flag = true
              //判断20分钟内多次报警记为一次情况
              jedis.hset("alm20min", id, oldTime)
              //驾驶时长
              drivingTime = cumulative_time
            }
          }
          var value = ""
          if ("".equals(driverName)) {
            value = cumulative_time.toString + "|" + oldTime + "|" + oldDriverName
          } else {
            value = cumulative_time.toString + "|" + oldTime + "|" + driverName
          }
          //数据存入redis
          jedis.hset("more4hours", id, value)

          var mum = 0
          if (data1 != null) {
            //如果速度小于20，则记录一次
            if (speed.toDouble <= 20.0) {
              val zeroTimes: Array[String] = data1.split("\\|")
              val str = jedis.hget("5timesmap", id)
              if (str != null) {
                val str1: Array[String] = str.split(",")
                if (str1.size < 5) {
                  jedis.hset("5timesmap", id, str1.mkString(",") + "," + zeroTimes(1))
                } else {
                  val endseat = str1.drop(1)
                  jedis.hset("5timesmap", id, endseat.mkString(",") + "," + zeroTimes(1))
                }
              } else {
                jedis.hset("5timesmap", id, zeroTimes(1))
              }
              mum = zeroTimes(2).toInt
              jedis.hset("speedZero", id, zeroTimes(0) + "|" + zeroTimes(1) + "|" + (mum + 1))
            } else {
              jedis.hdel("5timesmap", id)
              //map重新置为空
              jedis.hset("speedZero", id, 0 + "|" + oldTime + "|" + 0)
            }
          }
        } else {
          if (data1 != null) {
            val arr1: Array[String] = data1.split("\\|")
            val speed_value: Int = arr1(0).toInt
            val speed_time: String = arr1(1)
            val num: Int = arr1(2).toInt
            val dateTime_speed = DateTime.parse(speed_time, forPattern)
            val speedSeconds = Seconds.secondsBetween(dateTime_speed, dateTime_n).getSeconds
            var speed_newTime = speed_value
            var curSpeedTime = speed_time
            if (speedSeconds > 0) {
              speed_newTime = speed_value + speedSeconds
              curSpeedTime = time
            }
            val timemap: String = jedis.hget("5timesmap", id)
            if (timemap != null) {
              val timesarray = timemap.split(",")
              val datatime = DateTime.parse(timesarray(0), forPattern)
              val seconds1: Int = Seconds.secondsBetween(datatime, dateTime_n).getSeconds
              if (seconds1 >= 20 * 60) {
                val value = if ("".equals(driverName)) {
                  "0|" + curSpeedTime + "|" + oldDriverName
                } else {
                  "0|" + curSpeedTime + "|" + driverName
                }
                jedis.hset("more4hours", id, value)
                //周期重新累计时，删除挪车点
                jedis.hdel("5timesmap", id)
                flag = false
              } else {
                //继续累计时长
                jedis.hset("speedZero", id, speed_newTime.toString + "|" + curSpeedTime + "|" + num)
              }
            } else {
              if (speed_newTime >= 20 * 60 && num <= 5) {
                val value = if ("".equals(driverName)) {
                  "0|" + curSpeedTime + "|" + oldDriverName
                } else {
                  "0|" + curSpeedTime + "|" + driverName
                }
                jedis.hset("more4hours", id, value)
                //周期重新累计时，删除挪车点
                jedis.hdel("5timesmap", id)
                flag = false
              } else {
                //新增速度为0判断
                jedis.hset("speedZero", id, speed_newTime.toString + "|" + curSpeedTime + "|" + num)
              }
            }
          } else {
            jedis.hset("speedZero", id, "0|" + oldTime + "|0")
          }

        }
      } else {
        jedis.hset("more4hours", id, "0|" + time + "|" + driverName)
        flag = false
      }
    }
    (flag, drivingTime)
  }

  /**
    * 夜间连续驾驶2小时报警：夜间(22:00-06:00)定位数据中，
    * 驾驶员(未关联到驾驶员的按车辆)连续驾驶(断电不超过20分钟)超2小时生成报警
    *
    * @param time
    * @param primaryKey
    * @param jedis
    * @return
    */
  def nightDriver2hour(time: String, primaryKey: String, speed: String, jedis: Jedis, riskTimeDeploy: (Int, Int)): (Boolean, Int) = {
    val forPattern = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
    val id = primaryKey
    var flag = false
    var drivingTime = 0
    if (!time.isEmpty) {
      //获取时间 小时
      val date = DateTime.parse(time, forPattern)
      val minute = date.getMinuteOfDay
      //获取日间时间区间
      val start_time = riskTimeDeploy._1
      val end_time = riskTimeDeploy._2
      if (minute < end_time || minute >= start_time) {
        //获取redis数据
        val data: String = jedis.hget("more2hour", id)
        val data1: String = jedis.hget("2speedZero", id)
        //当前车辆驾驶信息
        val driverInfo: util.Map[String, String] = jedis.hgetAll("driverInfo:" + primaryKey)
        //当前车辆驾驶人
        var driverName = ""
        //人脸识别业务时间
        var businessTime = ""
        if (MapUtils.isNotEmpty(driverInfo) && driverInfo.containsKey("driverName")) {
          driverName = driverInfo.get("driverName")
          businessTime = driverInfo.get("businessTime")
        }
        //第一次判断redis是否有数据
        if (data != null) {
          //数据value值切分
          val arr: Array[String] = data.split("\\|")
          //累计时间差(s)
          val d_value = arr(0).toInt
          //上次记录的时间
          val origin_time = arr(1)
          //获取当前驾驶人
          driverName = CommonUtils.getCurrDriver(driverName, businessTime, origin_time, d_value, forPattern)
          //上次驾驶人
          var oldDriverName = ""
          if (arr.size == 3) {
            oldDriverName = arr(2)
          }
          val dateTime_o = DateTime.parse(origin_time, forPattern)
          val dateTime_n = DateTime.parse(time, forPattern)
          //时间差
          val seconds: Int = Seconds.secondsBetween(dateTime_o, dateTime_n).getSeconds
          var intervalSecond = seconds
          var oldTime = time
          if (seconds < 0) {
            oldTime = origin_time
            intervalSecond = 0
          }

          //断电超过20分钟 且速度为0
          if (seconds > 20 * 60 || (!"".equals(driverName) && !"".equals(oldDriverName) && !driverName.equals(oldDriverName))) {
            jedis.hset("more2hour", id, "0|" + oldTime + "|" + driverName)
            //周期重新累计时，删除挪车点
            jedis.hdel("5timesmap2", id)
            flag = false
          } else if (speed.toDouble > 0) {
            //断电不超过20分钟
            //累计时间
            val cumulative_time = d_value + intervalSecond
            //累计时间小于2小时不生成报警
            if (cumulative_time < 120 * 60) {
              flag = false
            } else if (cumulative_time >= 120 * 60) {
              val minutes_num: String = jedis.hget("2alm20min", id)
              if (minutes_num != null) {
                val time1: DateTime = DateTime.parse(minutes_num, forPattern)
                val tim_n = Seconds.secondsBetween(time1, dateTime_n).getSeconds
                if (tim_n > 20 * 60) {
                  flag = true
                  //重置20分钟的第一次报警时间
                  jedis.hset("2alm20min", id, oldTime)
                  //驾驶时长
                  drivingTime = cumulative_time
                } else {
                  flag = false
                }
              } else {
                //生成报警
                flag = true
                //判断20分钟内多次报警记为一次情况
                jedis.hset("2alm20min", id, oldTime)
                //驾驶时长
                drivingTime = cumulative_time
              }
            }
            val value = if ("".equals(driverName)) {
              cumulative_time.toString + "|" + oldTime + "|" + oldDriverName
            } else {
              cumulative_time.toString + "|" + oldTime + "|" + driverName
            }
            //数据存入redis
            jedis.hset("more2hour", id, value)
            var mum = 0
            if (data1 != null) {
              //如果速度小于20，则记录一次
              if (speed.toDouble <= 20.0) {
                val zeroTimes: Array[String] = data1.split("\\|")
                val str = jedis.hget("5timesmap2", id)
                if (str != null) {
                  val str1: Array[String] = str.split(",")
                  if (str1.size < 5) {
                    jedis.hset("5timesmap2", id, str1.mkString(",") + "," + zeroTimes(1))
                  } else {
                    val endseat = str1.drop(1)
                    jedis.hset("5timesmap2", id, endseat.mkString(",") + "," + zeroTimes(1))
                  }
                } else {
                  jedis.hset("5timesmap2", id, zeroTimes(1))
                }
                mum = zeroTimes(2).toInt
                jedis.hset("2speedZero", id, zeroTimes(0) + "|" + zeroTimes(1) + "|" + (mum + 1))
              } else {
                jedis.hdel("5timesmap2", id)
                //map重新置为空
                jedis.hset("2speedZero", id, 0 + "|" + oldTime + "|" + 0)
              }
            }
          } else {
            if (StringUtils.isNotEmpty(data1)) {
              val arr1: Array[String] = data1.split("\\|")
              val speed_value: Int = arr1(0).toInt
              val speed_time: String = arr1(1)
              var num: Int = 0
              if(data1.size == 3){
                num = arr(2).toInt
              }
              val dateTime_speed = DateTime.parse(speed_time, forPattern)
              val speedSeconds = Seconds.secondsBetween(dateTime_speed, dateTime_n).getSeconds.abs
              var speed_newTime = speed_value
              var curSpeedTime = speed_time
              if (speedSeconds > 0) {
                speed_newTime = speed_value + speedSeconds
                curSpeedTime = time
              }
              val timemap: String = jedis.hget("5timesmap2", id)
              if (timemap != null) {
                val timesarray = timemap.split(",")
                val datatime = DateTime.parse(timesarray(0), forPattern)
                val seconds1: Int = Seconds.secondsBetween(datatime, dateTime_n).getSeconds
                if (seconds1 >= 20 * 60) {
                  val value = if ("".equals(driverName)) {
                    "0|" + curSpeedTime + "|" + oldDriverName
                  } else {
                    "0|" + curSpeedTime + "|" + driverName
                  }
                  jedis.hset("more2hours", id, value)
                  //周期重新累计时，删除挪车点
                  jedis.hdel("5timesmap2", id)
                  flag = false
                } else {
                  //继续累计时长
                  jedis.hset("2speedZero", id, speed_newTime.toString + "|" + curSpeedTime + "|" + num)
                }
              } else {
                if (speed_newTime >= 20 * 60 && num <= 5) {
                  val value = if ("".equals(driverName)) {
                    "0|" + curSpeedTime + "|" + oldDriverName
                  } else {
                    "0|" + curSpeedTime + "|" + driverName
                  }
                  jedis.hset("more2hours", id, value)
                  //周期重新累计时，删除挪车点
                  jedis.hdel("5timesmap2", id)
                  flag = false
                } else {
                  //新增速度为0判断
                  jedis.hset("2speedZero", id, speed_newTime.toString + "|" + curSpeedTime + "|" + num)
                }
              }
            } else {
              jedis.hset("2speedZero", id, "0|" + oldTime + "|0")
            }
          }
        } else {
          jedis.hset("more2hour", id, "0|" + time + "|" + driverName)
          flag = false
        }
      }
    }
    (flag, drivingTime)
  }

  /**
    * 2-5点凌晨禁行：凌晨2:00-5:00,有速度信号的累计驾驶时长大于0
    *
    * @param time 时间
    * @param vec1 卫星定位速度
    * @param vec2 车载设备速度
    * @param id   车牌号+车牌颜色
    * @param vec3 车辆行驶里程
    * @param lon  经度
    * @param lat  维度
    * @param jedis
    * @return
    */
  def prohibitDrive(time: String, vec1: String, vec2: String, id: String,
                    vec3: String, lon: String, lat: String, jedis: Jedis): Boolean = {
    var flag: Boolean = false
    val forPattern = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
    if (StringUtils.isNotEmpty(time)) {
      //获取时间 小时
      val date = DateTime.parse(time, forPattern)
      val str = date.getHourOfDay
      //时间区间在凌晨2点到凌晨5点
      if (str.toInt >= 2 && str.toInt < 5) {
        //获取上次运行时间
        val run_time: String = jedis.hget("runtime", id)
        //上次运行时间为空判断
        if (run_time != null) {
          //上次时间与当次时间
          val dateTime_o = DateTime.parse(run_time, forPattern)
          val dateTime_n = DateTime.parse(time, forPattern)
          val seconds: Int = Seconds.secondsBetween(dateTime_o, dateTime_n).getSeconds
          if (seconds > 0) {
            jedis.hset("runtime", id, time)
          }
          if (vec1 != null) {
            if (vec1.toDouble > 0.0) { //先判断卫星定位速度
              val minutes_num: String = jedis.hget("alm10min", id)
              if (minutes_num != null) {
                val time1: DateTime = DateTime.parse(minutes_num, forPattern)
                val tim_n = Seconds.secondsBetween(time1, dateTime_n).getSeconds
                if (tim_n > 5 * 60) {
                  flag = true
                  //重置5分钟的第一次报警时间
                  jedis.hset("alm10min", id, time)
                } else {
                  flag = false
                }
              } else {
                //生成报警
                flag = true
                //判断10分钟内多次报警记为一次情况
                jedis.hset("alm10min", id, time)
              }
            } else {
              if (vec2 != null) {
                if (vec2.toDouble > 0.0) { //再判断行车设备速度
                  val minutes_num: String = jedis.hget("alm10min", id)
                  if (minutes_num != null) {
                    val time1: DateTime = DateTime.parse(minutes_num, forPattern)
                    val tim_n = Seconds.secondsBetween(time1, dateTime_n).getSeconds
                    if (tim_n > 5 * 60) {
                      flag = true
                      //重置5分钟的第一次报警时间
                      jedis.hset("alm10min", id, time)
                    } else {
                      flag = false
                    }
                  } else {
                    //生成报警
                    flag = true
                    //判断10分钟内多次报警记为一次情况
                    jedis.hset("alm10min", id, time)
                  }
                } else {
                  val vec: String = jedis.hget("carMileage", id)
                  var ve = 0.0
                  if (vec3 != null) {
                    ve = vec3.toDouble
                  } else {
                    ve = 0.0
                  }
                  var vecc = 0.0
                  if (vec != null) {
                    vecc = vec.toDouble
                  } else {
                    vecc = 0.0
                  }
                  if (vecc < ve) { //判断行驶里程大于上次的行驶里程
                    jedis.hset("carMileage", id, vec3)
                    val minutes_num: String = jedis.hget("alm10min", id)
                    if (minutes_num != null) {
                      val time1: DateTime = DateTime.parse(minutes_num, forPattern)
                      val tim_n = Seconds.secondsBetween(time1, dateTime_n).getSeconds
                      if (tim_n > 5 * 60) {
                        flag = true
                        //重置10分钟的第一次报警时间
                        jedis.hset("alm10min", id, time)
                      } else {
                        flag = false
                      }
                    } else {
                      //生成报警
                      flag = true
                      //判断10分钟内多次报警记为一次情况
                      jedis.hset("alm10min", id, time)
                    }
                  } else { //判断经纬度是否变化
                    val lon_lat: String = jedis.hget("lonLat", id)
                    if (lon_lat != null && lon != null && lat != null) {
                      val lon_and_lat: Array[String] = lon_lat.split("\\|")
                      //经度
                      val lons: String = lon_and_lat(0)
                      //维度
                      val lats: String = lon_and_lat(1)
                      val distance: Double = CommonUtils.getDistance(lats.toDouble, lons.toDouble, lat.toDouble, lon.toDouble)
                      if (distance > 0.3D) {
                        jedis.hset("lonLat", id, lon + "|" + lat)
                        val minutes_num: String = jedis.hget("alm10min", id)
                        if (minutes_num != null) {
                          val time1: DateTime = DateTime.parse(minutes_num, forPattern)
                          val tim_n = Seconds.secondsBetween(time1, dateTime_n).getSeconds
                          if (tim_n > 5 * 60) {
                            flag = true
                            //重置5分钟的第一次报警时间
                            jedis.hset("alm10min", id, time)
                          } else {
                            flag = false
                          }
                        } else {
                          //生成报警
                          flag = true
                          //判断5分钟内多次报警记为一次情况
                          jedis.hset("alm10min", id, time)
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      } else {
        jedis.hset("runtime", id, time)
        if (vec3 == null) {
          jedis.hset("carMileage", id, "0")
        } else {
          jedis.hset("carMileage", id, vec3)
        }
        if (lon != null && lat != null) {
          jedis.hset("lonLat", id, lon + "|" + lat)
        }
        flag = false
      }
    }
    flag
  }

  /**
    * 有速度无驾驶人身份报警
    *
    * @param redis
    * @param speed
    * @param primaryKey
    * @return
    */
  def noDriverInfo(redis: Jedis, speed: String, primaryKey: String): Boolean = {
    var flag: Boolean = false
    val driverInfo: util.Map[String, String] = redis.hgetAll("driverInfo:" + primaryKey)
    if (speed.toDouble > 0) {
      if (null != driverInfo && driverInfo.containsKey("driverName")) {
        val driverName = driverInfo.get("driverName")
        val exist = CommonUtils.checkChinese(driverName)
        flag = !exist
      } else {
        flag = true
      }
    }
    flag
  }

  /**
    * 20公里有无分神或者20公里有无变道
    *
    * @param redis
    * @param key
    * @param primaryKey
    * @param lat1
    * @param lng1
    * @return
    */
  def equipmentValid(redis: Jedis, key: String, primaryKey: String, lat1: String, lng1: String): Boolean = {
    var falg = false
    val data = redis.hget(key, primaryKey)
    if (data != null) {
      val splits = data.split("\\|")
      val lat2 = splits(0)
      val lng2 = splits(1)
      val distance: Double = CommonUtils.getDistance(lat1.toDouble, lng1.toDouble, lat2.toDouble, lng2.toDouble)
      if (4 == splits.size) {
        val lastLat = splits(2)
        val lastLng = splits(3)
        val lastDistance = CommonUtils.getDistance(lat1.toDouble, lng1.toDouble, lastLat.toDouble, lastLng.toDouble)
        if (distance >= 20 && lastDistance >= 20) {
          redis.hset(key, primaryKey, lat2 + "|" + lng2 + "|" + lat1 + "|" + lng1)
          falg = true
        }
      } else {
        if (distance >= 20) {
          redis.hset(key, primaryKey, data + "|" + lat1 + "|" + lng1)
          falg = true
        }
      }
    }
    falg
  }

  /**
    * 3公里有无分神或者有无变道,并且行驶时长是否达到20分钟
    * @param redis
    * @param key
    * @param primaryKey
    * @param lastTotalTime
    * @param distance
    * @return
    */
  def equipmentWarnValid(redis: Jedis, key: String, primaryKey: String, lastTotalTime: Int, distance: Double): Boolean = {
    var falg = false
    val data = redis.hget(key, primaryKey)
    if(lastTotalTime >= 1200 && distance >= 3.0D){
      if (StringUtils.isNotEmpty(data)) {
        if(data.toInt == 0){
          falg = true
        }
        redis.hdel(key, primaryKey)
      }else{
        falg = true
      }
    }

    falg
  }

  /**
    * 车道偏离报警和分神驾驶报警存到redis
    *
    * @param redis
    * @param lat1
    * @param lng1
    * @param primaryKey
    * @param eventType
    * @return
    */
  def distractedWarnSave(redis: Jedis, lat1: String, lng1: String, primaryKey: String, warnType: String, eventType: String): Unit = {
    //车道偏离报警
    if ("0x0064".equals(warnType) && "0x02".equals(eventType)) {
      redis.hset("adasDevice20", primaryKey, lat1 + "|" + lng1)
    }
    //分神驾驶报警
    if ("0x0065".equals(warnType) && "0x04".equals(eventType)) {
      redis.hset("dsmDevice20", primaryKey, lat1 + "|" + lng1)
    }
  }

  /**
    * 车道偏离报警、分神驾驶报警和人脸识别报警存到redis
    * 贵阳无even_type,已删除
    * @param redis
    * @param primaryKey
    * @param warnType
    */
  def deviceWarnUpdate(redis: Jedis, primaryKey: String, warnType: String): Unit = {
    //车道偏离报警
    if ("0x00103".equals(warnType)) {
      redis.hincrBy("adasDevice", primaryKey, 1)
    }
    //分神驾驶报警
    if ("0x00107".equals(warnType)) {
      redis.hincrBy("dsmDevice", primaryKey, 1)
    }
    //人脸识别报警数据
    if("0x0065".equals(warnType)){
      redis.hincrBy("driverFacialRecognition", primaryKey, 1)
    }
  }
}
